'use strict';

import './popup.css';

(function() {
  var SETTINGS = '___DATA_COPY:SETTINGS'

  var $dataCopyStorage = {
    get: (key, cb) => {
      chrome.storage.local.get([key], result => {
        cb(result[key]);
      });
    },
    set: (key, value, cb) => {
      chrome.storage.local.set(
        {
          [key]: value,
        },
        () => {
          cb && cb();
        }
      );
    },
  };

  var $dataCopyData = {
    settings: {
      listenSite: '',
      listenStatus: '',
      source: [{
        selectorName: '', 
        storageKey: ''
      }],
      target: [{
        selectorName: '',
        storageKey: ''
      }]
    },
    source: {
      refreshDate: new Date(),
      settings: [{
        selectorName: '', 
        storageKey: '',
        domExist: false,
        value: undefined,
        autoSave: false, // 自动保存
      }]
    },
    target: {
      refreshDate: new Date(),
      settings: [{
        selectorName: '', 
        storageKey: '',
        domExist: false,
        value: undefined,
        targetValue: undefined
      }]
    }
  }

  var $dataCopyUI = {
    activeId: 'target',
    refreshSettingsTab() {
      $('.tab-content-item[data-id=settings]').html(this.initSettingsTabHtml)
      this.setupTab("settings")
    },
    setupTab(tab) {
      this.$tabNavs = $('.tab-nav .tab-nav-item')
      this.$tabContents = $('.tab-content .tab-content-item')
      this.initSettingsTabHtml = $('.tab-content-item[data-id=settings]').html()

      this.activeTab(tab)
      this.$tabNavs.on('click', (evt) => {
        var id = evt.target.dataset['id']
        this.activeTab(id)

        if(id === 'target') {
          getTargetDomValue()
        }
        if(id === 'source') {
          getSourceDomValue()
        }
      })

      this.$addSource = $('#addSource')
      this.$addTarget = $('#addTarget')
      this.$applaySetting = $('#applaySetting')
      this.$saveSource = $('#saveSource')
      this.$setTarget = $('#setTarget')
      this.$refreshTarget = $('#refreshTarget')
      this.$refreshSource = $('#refreshSource')
      this.$listenSite = $('#listenSite')
      this.$listenStatus = $('#listenStatus')
      this.$exportSetting = $('#exportSetting')
      this.$importSetting = $('#importSetting')

      this.$sourceForm = $('.source-form .form')
      this.$targetForm = $('.target-form .form')
      
      this.$addSource.on('click', () => this.appendSourceForm.bind(this)())
      this.$addTarget.on('click', () => this.appendTargetForm.bind(this)())
      this.$applaySetting.on('click', applaySetting)
      this.$saveSource.on('click', saveSource)
      this.$setTarget.on('click', setTargetDomValue)

      this.$refreshTarget.on('click', getTargetDomValue)
      this.$refreshSource.on('click', getSourceDomValue)

      this.$exportSetting.on('click', exportSetting)
      this.$importSetting.on('click', importSetting)

      this.$listenSite.val($dataCopyData.settings.listenSite)
      this.$listenStatus.val($dataCopyData.settings.listenStatus)

      var sourceArray = $dataCopyData.settings.source || []
      var targetArray = $dataCopyData.settings.target || []
      sourceArray.forEach((item)=> {
        $dataCopyUI.appendSourceForm(item)
      })
      targetArray.forEach((item)=> {
        $dataCopyUI.appendTargetForm(item)
      })

      getSourceDomValue()
      getTargetDomValue()
    },
    activeTab(key) {
      this.activeId = key
      this.$tabNavs.removeClass('active')
      this.$tabContents.removeClass('active')
      $(`.tab-nav .tab-nav-item[data-id=${key}]`).addClass('active')
      $(`.tab-content .tab-content-item[data-id=${key}]`).addClass('active')
    },
    appendSourceForm(item) {
      var form = $(`
        <form class="form-item-group">
          <div class="form-item-group-item">
            <div class="form-item-label">元素</div>
            <div class="form-item-control">
              <input name="selectorName" />
            </div>
          </div>
          <div class="form-item-group-item">
            <div class="form-item-label">存储</div>
            <div class="form-item-control">
              <input name="storageKey" />
            </div>
          </div>
          <div class="form-item-group-actions">
            <div class="btn btn-link btn-delete">删除</div>
          </div>
        </form>
      `)
      if(item) {
        $(form[0][0]).val(item.selectorName || '')
        $(form[0][1]).val(item.storageKey || '')
      }

      var $delete = form.find('.btn-delete')
      $delete.on('click', () => {
        form.remove()
      })

      this.$sourceForm.append(form)
    },
    appendTargetForm(item) {
      var form = $(`
        <form class="form-item-group">
          <div class="form-item-group-item">
            <div class="form-item-label">元素</div>
            <div class="form-item-control">
              <input name="selectorName" />
            </div>
          </div>
          <div class="form-item-group-item">
            <div class="form-item-label">存储</div>
            <div class="form-item-control">
              <input name="storageKey" />
            </div>
          </div>
          <div class="form-item-group-actions">
            <div class="btn btn-link btn-delete">删除</div>
          </div>
        </form>
      `)
      if(item) {
        $(form[0][0]).val(item.selectorName || '')
        $(form[0][1]).val(item.storageKey || '')
      }

      var $delete = form.find('.btn-delete')
      $delete.on('click', () => {
        form.remove()
      })

      this.$targetForm.append(form)
    },
    applaySetting() {
      var sourceFormArray = this.$sourceForm.children().serializeArray()
      var sourceArray = []
      for(var i = 0; i * 2 < sourceFormArray.length; i++) {
        var selectorName = sourceFormArray[i*2].value
        var storageKey = sourceFormArray[i*2+1].value
        sourceArray.push({
          selectorName,
          storageKey
        })
      }

      var targetFormArray = this.$targetForm.children().serializeArray()
      var targetArray = []
      for(var i = 0; i * 2 < targetFormArray.length; i++) {
        var selectorName = targetFormArray[i*2].value
        var storageKey = targetFormArray[i*2+1].value
        targetArray.push({
          selectorName,
          storageKey
        })
      }
      return {
        listenSite: this.$listenSite.val(),
        listenStatus: this.$listenStatus.val(),
        source: sourceArray,
        target: targetArray
      }
    },
    refreshSource() {
      // 刷新UI
      var $sourceForm = $('.tab-content .tab-content-item[data-id=source] .form')
      var settings = $dataCopyData.source.settings || []
      $sourceForm.empty()
      settings.forEach((item)=> {
        if(item.domExist) {
          $sourceForm.append(`<div>源元素<code>${item.selectorName}</code>值<code>${item.value}</code></div>`)
        } else {
          $sourceForm.append(`<div>源元素<code>${item.selectorName}</code>不存在</div>`)
        }
      })
    },
    refreshTarget() {
      // 刷新UI
      var $targetForm = $('.tab-content .tab-content-item[data-id=target] .form')
      var settings = $dataCopyData.target.settings || []
      $targetForm.empty()
      settings.forEach((item)=> {
        if(item.domExist) {
          $targetForm.append(`<div>目标元素<code>${item.selectorName}</code>目前值<code>${item.value}</code>将被替换成<code>${item.targetValue}</code></div>`)
        } else {
          $targetForm.append(`<div>目标元素<code>${item.selectorName}</code>不存在</div>`)
        }
      })
    }
  }

  function onLoad() {
    setupSetting()
  }

  // 读取配置(设置)
  function setupSetting(tab) {
    console.log('读取配置(设置)')
    $dataCopyStorage.get(SETTINGS, (settings)=> {
      $dataCopyData.settings = settings || {
        listenSite: '',
        listenStatus:'',
        source: [],
        target: []
      }
      $dataCopyUI.setupTab(tab || 'target')
    })
  }

  // 应用配置(设置)
  function applaySetting() {
    console.log('应用配置(设置)')
    $dataCopyData.settings = $dataCopyUI.applaySetting()
    $dataCopyStorage.set(SETTINGS, $dataCopyData.settings, getSourceDomValue)
    alert("保存成功")
  }

  // 刷新（来源）
  function refreshSource() {
    console.log('刷新（来源）')
    $dataCopyUI.refreshSource()
  }

  // 刷新（目标）
  function refreshTarget() {
    console.log('刷新（目标）')
    $dataCopyUI.refreshTarget()
  }

  // 获取dom值（来源）
  function getSourceDomValue() {
    console.log('获取dom值（来源）')
    var sourceArray = $dataCopyData.settings.source || []
    var settingsArray = []
    sourceArray.forEach((item)=> {
      var data = {
        selectorName: item.selectorName,
        storageKey: item.storageKey
      }
      getDomValue(item.selectorName, 'source', (evt) => {
        data.value = evt.value
        data.domExist = evt.domExist
        settingsArray.push(data)

        if(settingsArray.length === sourceArray.length) {
          $dataCopyData.source.settings = settingsArray
          refreshSource(settingsArray)
        }
        
      })
    })
  }

  // 设置(目标)
  function setTargetDomValue() {
    console.log('设置(目标)')
    var settins = $dataCopyData.target.settings || []
    settins.forEach((item) => {
      setDomValue(item.selectorName, item.targetValue, ()=> {})
    })

    setTimeout(() => getTargetDomValue(), 300)
  }

  // 保存(来源)
  function saveSource() {
    console.log('保存(来源)')
    var settins = $dataCopyData.source.settings || []
    settins.forEach((item) => {
      $dataCopyStorage.set(item.storageKey, item.value)
    })
  }

   // 获取dom值（目标）
  function getTargetDomValue() {
    console.log('获取dom值（目标）')
    var targetArray = $dataCopyData.settings.target || []
    var settingsArray = []
    targetArray.forEach((item)=> {
      var data = {
        selectorName: item.selectorName,
        storageKey: item.storageKey
      }
      $dataCopyStorage.get(data.storageKey, (value)=> {
        data.targetValue = value
      })
      getDomValue(item.selectorName, 'target', (evt) => {
        data.value = evt.value
        data.domExist = evt.domExist
        settingsArray.push(data)
        if(settingsArray.length === targetArray.length) {
          $dataCopyData.target.settings = settingsArray
          refreshTarget(settingsArray)
        }
      })
    })
  }

  // 获取当前tab中dom的值
  function getDomValue(selectorName, type, callback) {
    chrome.tabs.query({ active: true, currentWindow: true }, tabs => {
      const tab = tabs[0];
      chrome.tabs.sendMessage(
        tab.id,
        {
          type: 'getDomValue',
          payload: {
            selectorName,
            type
          },
        },
        response => {
          console.log('getDomValue response is ', response);
          if(response) callback(response)
        }
      );
    });
  }

  // 设置当前tab中dom的值
  function setDomValue(selectorName, value, callback) {
    chrome.tabs.query({ active: true, currentWindow: true }, tabs => {
      const tab = tabs[0];
      chrome.tabs.sendMessage(
        tab.id,
        {
          type: 'setDomValue',
          payload: {
            selectorName,
            value: value
          },
        },
        response => {
          console.log('setDomValue response is ', response);
          callback(response)
        }
      );
    });
  }

  function exportSetting() {
    var url = 'data:application/json;base64,' + btoa(JSON.stringify($dataCopyData.settings));
    chrome.downloads.download({
        url: url,
        saveAs: false,
        filename: 'web-data-copy-settings.json',
        conflictAction: "overwrite"
    });
  }

  function importSetting() {
    var input = document.createElement('input')
    input.type = 'file'
    input.accept = 'application/json'
    input.onchange = (evt)=> {
      var file = evt.target.files[0]
      var fileReader = new FileReader()
      fileReader.onload = (evt)=> {
        var content = evt.currentTarget.result
        $dataCopyData.settings = JSON.parse(content)
        $dataCopyStorage.set(SETTINGS, $dataCopyData.settings, () => $dataCopyUI.refreshSettingsTab())
      }
      fileReader.readAsText(file, 'utf-8')
    }
    input.click()
  }

  document.addEventListener('DOMContentLoaded', onLoad);
})();
